//  重新封装原生路由方法
let routerFilter = function noop() {}
/**
 * 对wx.navigateTo的封装
 * @param {路由} path
 * @param {参数} params
 * @param {事件} events
 */
const push = (path, params, events) => {
  routerFilter();
  let query = "";
  for (const key in params) {
    if (Object.hasOwnProperty.call(params, key)) {
      const element = params[key];
      query += `${key}=${element}&`;
    }
  }
  wx.navigateTo({
    url: path + `?${query}`,
    events: events,
    success(res) {
      wx.Logger(res);
    },
    fail(err) {
      wx.Logger(err);
    },
  });
};

/**
 * 对wx.redirectTo的封装
 * @param {路由} path
 * @param {参数} params
 */
const replace = (path, params) => {
  routerFilter();
  let query = "";
  for (const key in params) {
    if (Object.hasOwnProperty.call(params, key)) {
      const element = params[key];
      query += `${key}=${element}&`;
    }
  }
  wx.redirectTo({
    url: path + `?${query}`,
    success(res) {
      wx.Logger(res);
    },
    fail(err) {
      wx.Logger(err);
    },
  });
};

/**
 * 对wx.navigateBack的封装
 * @param {返回的层级} number
 */
const pop = (number) => {
  routerFilter();
  wx.navigateBack({
    delta: number,
    success(res) {
      wx.Logger(res);
    },
    fail(err) {
      wx.Logger(err);
    },
  });
};

/**
 * 对wx.reLaunch的封装
 * @param {路由} path
 * @param {参数} params
 */
const relaunch = (path, params) => {
  routerFilter();
  let query = "";
  for (const key in params) {
    if (Object.hasOwnProperty.call(params, key)) {
      const element = params[key];
      query += `${key}=${element}&`;
    }
  }
  wx.reLaunch({
    url: path + `?${query}`,
    success(res) {
      wx.Logger(res);
    },
    fail(err) {
      wx.Logger(err);
    },
  });
};

/**
 * 对tabbar的封装
 * @param {路由} path
 */
const switchTab = (path) => {
  routerFilter();
  wx.switchTab({
    url: path,
    success(res) {
      wx.Logger(res);
    },
    fail(err) {
      wx.Logger(err);
    },
  });
};

wx.$router = {
  push,
  replace,
  pop,
  relaunch,
  switchTab,
}